<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="150px"
    >
      <el-form-item label="报价单号" prop="no">
        <el-input
          v-model="queryParams.salesNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户名称/编号" prop="cusName">
        <el-input
          v-model="queryParams.cusName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="productId">
        <el-select
          v-model="queryParams.productId"
          clearable
          filterable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="productId">
        <el-select
          v-model="queryParams.productId"
          clearable
          filterable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input
          v-model="queryParams.spec"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品物料属性" prop="materialAttribute">
        <el-input
          v-model="queryParams.materialAttribute"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:sale-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>

        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:sale-order:export']"
        >
          <Icon icon="ep:upload" />导出
        </el-button>
        <el-button size="default" @click="handleImport">
          <Icon icon="ep:download" class="mr-5px" /> 导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-row :gutter="10" class="flex-justify-between w-full" style="margin-bottom: 16px">
      <div class="flex">
        <el-col :span="1.5">
          <div>
            <el-dropdown placement="bottom-start">
              <el-button> 生成单据 </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>合同</el-dropdown-item>
                  <el-dropdown-item>设计单</el-dropdown-item>
                  <el-dropdown-item>销售订单</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-col>
      </div>
      <div class="flex items-center">
        <el-col :span="1.5">
          <span class="text-[14px] mr-[4px] color-#606266">整单</span>
          <el-switch v-model="order" size="middle" />
        </el-col>
        <el-col :span="1.5" v-if="!wholeOrderMode">
          <span class="text-[14px] mr-[4px] color-#606266">单据类型</span>
          <el-select v-model="value" placeholder="请选择" style="width: 100px">
            <el-option value="1">产品</el-option>
            <el-option value="2">物料</el-option>
          </el-select>
        </el-col>
        <el-col :span="10.1">
          <div style="text-align: right">
            <el-button type="default" plain @click="btnLie">
              <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
              列表字段
            </el-button>
          </div>
        </el-col>
      </div>
    </el-row>
    <el-table
      v-loading="loading"
      :data="wholeOrderMode ? wholeOrderList : list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="30" label="选择" type="selection" />

      <!-- 动态列 -->
      <template v-if="!wholeOrderMode">
        <el-table-column label="单据状态" align="center" prop="documentStatus" />
        <el-table-column label="报价单号" align="center" prop="bjNo" />
        <el-table-column label="销售类型" align="center" prop="salesType" />
        <el-table-column label="审核状态" align="center" prop="auditStatus" />
        <el-table-column label="客户名称" align="center" prop="cusName" />
        <el-table-column label="客户编码" align="center" prop="cusCode" />
        <el-table-column label="报价开始时间" align="center" prop="bjStartTime" />
        <el-table-column label="报价结束时间" align="center" prop="bjEndTime" />
        <el-table-column label="摘要" align="center" prop="abstract" />
        <el-table-column label="客户订单编号" align="center" prop="cusOrderCode" />
        <el-table-column label="是否过期" align="center" prop="isPass" />
        <el-table-column label="报价使用状态" align="center" prop="bjUseStatuw" />
      </template>
      <template v-else>
        <!-- 整单模式列 -->
        <el-table-column
          v-for="col in wholeOrderColumns"
          :key="col.prop"
          :label="col.label"
          :prop="col.prop"
          :width="col.width"
          align="center"
        />
      </template>

      <el-table-column label="操作" align="center" fixed="right" width="220">
        <template #default="scope">
          <el-button
            link
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['erp:sale-order:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:sale-order:update']"
            :disabled="scope.row.status === 20"
          >
            打印
          </el-button>

          <el-button
            link
            type="primary"
            @click="openForm('print', scope.row.id)"
            v-hasPermi="['erp:sale-order:update']"
            :disabled="scope.row.status === 20"
          >
            打印记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <bjForm ref="formRef" @success="getList" />
  <!-- <CustomerImportForm ref="importFormRef" @success="getList" /> --> 
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import bjForm from './bjForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
// import CustomerImportForm from '@/views/crm/customer/CustomerImportForm.vue'

/** ERP 销售订单列表 */
defineOptions({ name: 'ErpSaleOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SaleOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  productId: undefined,
  orderTime: [],
  status: undefined,
  remark: undefined,
  creator: undefined,
  outStatus: undefined,
  returnStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<any>([]) // 产品列表
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserVO[]>([]) // 用户列表
const order = ref(false)
// 新增状态管理
const wholeOrderMode = ref(false) // 整单模式标志
const wholeOrderList = ref([]) // 整单模式专用数据

// 整单模式列配置
const wholeOrderColumns = ref([
  { prop: 'salesStatus', label: '销售类型' },
  { prop: 'bjOrder', label: '报价单号' },
  { prop: 'auditStatus', label: '审核状态'},
  { prop: 'orderStatus', label: '单据状态'},
  { prop: 'cusCode', label: '客户编号' },
  { prop: 'cusName', label: '客户名称'},
  { prop: 'bjStartTime', label: '报价开始时间' },
  { prop: 'bjEndTime', label: '报价结束时间' },
  { prop: 'abstract', label: '摘要' },
  { prop: 'isPass', label: '是否过期' },
  { prop: 'bjUseStatus', label: '报价使用状态' },
])

// 监听整单开关变化
watch(order, async (newVal) => {
  wholeOrderMode.value = newVal
  if (newVal) {
    await fetchWholeOrderData()
  } else {
    getList() // 切换回普通模式
  }
})

// 整单模式专用数据获取
const fetchWholeOrderData = async () => {
  loading.value = true
  try {
    const response = await fetch('https://api.example.com/sale-orders/whole', {
      method: 'POST',
      body: JSON.stringify({
        ...queryParams,
        wholeOrder: true // 添加特殊参数
      })
    })
    wholeOrderList.value = await response.json()
  } finally {
    loading.value = false
  }
}
/** 导入按钮操作 */
const importFormRef = ref<InstanceType<typeof CustomerImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleOrderApi.getSaleOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SaleOrderApi.deleteSaleOrder(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

/** 审批/反审批操作 */
const handleUpdateStatus = async (id: number, status: number) => {
  try {
    // 审批的二次确认
    await message.confirm(`确定${status === 20 ? '审批' : '反审批'}该订单吗？`)
    // 发起审批
    await SaleOrderApi.updateSaleOrderStatus(id, status)
    message.success(`${status === 20 ? '审批' : '反审批'}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleOrderApi.exportSaleOrder(queryParams)
    download.excel(data, '报价单管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中操作 */
const selectionList = ref<SaleOrderVO[]>([])
const handleSelectionChange = (rows: SaleOrderVO[]) => {
  selectionList.value = rows
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表、客户
  // productList.value = await ProductApi.getProductSimpleList()
  // customerList.value = await CustomerApi.getCustomerSimpleList()
  userList.value = await UserApi.getSimpleUserList()
})
// TODO 芋艿：可优化功能：列表界面，支持导入
// TODO 芋艿：可优化功能：详情界面，支持打印
</script>
